package usersOnlineService

import (
	"chart.zozoo.net/app/dao/usersOnlineDao"
	"chart.zozoo.net/app/models"
	"chart.zozoo.net/core/myRedis"
	"encoding/json"
	"time"
)

// Info 获取用户在线状态
func Info(uuid string, params ...string) (online *models.UserOnline, err error) {
	online = &models.UserOnline{}
	up := "get"
	if len(params) > 0 {
		up = params[0]
	}

	redisKey := "userOnline:uid:" + uuid + ":json"
	switch up {
	case "update":
		break
	case "delete":
		myRedis.RedisClient.Del(redisKey)
		return
	default:
		//判断缓存是否存在
		res := myRedis.RedisClient.Get(redisKey)
		if res.Err() == nil {
			err = json.Unmarshal([]byte(res.Val()), online)
			if err != nil {
				return nil, err
			}

			return online, nil
		}

		//缓存不存在，查询数据库
		online, err = usersOnlineDao.Info(uuid)
		if err != nil {
			return nil, err
		}

		//保存缓存
		bytes, err := json.Marshal(online)
		if err != nil {
			return nil, err
		}

		myRedis.RedisClient.Set(redisKey, string(bytes), time.Hour*24)
		return online, nil
	}

	return
}
